<template>
  <div class="container">
    <div class="main_content">
      <div class="main_left">
        <div class="main_topic">
          <!--   main-connect内容   -->
          <div class="answer_list" v-for="(item, index) in answerExamData" :key="index">
            <div class="answer_question">
              <!--  包含html    -->
              <div v-if="$isIncludesHtml(item.content)" class="question_content line_feed"
                   v-html="`${item.content.slice(0,3)}${topicIndex+1}.<span class='color_orange'>【${$store.getters.topicTypeText[item.topicType]}】</span>${$renderedDescription(item.content.slice(3))}`"
              ></div>
              <!--  不包含html    -->
              <div v-else class="question_content line_feed"
                   v-html="`${topicIndex+1}.<span class='color_orange'>【${$store.getters.topicTypeText[item.topicType]}】</span>${$renderedDescription(item.content)}`"
              ></div>
              <div class="item_answer">
                <template v-if="submitType==1">
                  <!--    填空题部分        -->
                  <div v-if="item.topicType == 3">
                    <div
                      class="blank_item"
                      v-for="(optionItem, optionIndex) in item.optionCount"
                      :key="optionIndex"
                    >
                      <span class="blank_item_label">{{ optionIndex + 1 }}.</span>
                      <el-input
                        v-if="!$isIncludesHtml(item.multiAnswers[optionIndex])"
                        clearable
                        class="blank_item_answer"
                        type="text"
                        placeholder="请输入答案"
                        v-model="item.multiAnswers[optionIndex]"
                      ></el-input>
                      <div v-else class="formula_text" v-html="$renderedDescription(item.multiAnswers[optionIndex])"></div>
                      <div v-if="!$isIncludesHtml(item.multiAnswers[optionIndex]) && !item.multiAnswers[optionIndex]"
                           @click="getValueByFormula(item,optionIndex)" class="icon_box"
                      >
                        <svg-icon class-name="formula_icon" icon-class="formula_scg"></svg-icon>
                      </div>
                      <div v-if="$isIncludesHtml(item.multiAnswers[optionIndex])" @click="clearFormulaValue(item,optionIndex)" class="icon_box">
                        <i class="el-icon-delete"></i>
                      </div>
                    </div>
                  </div>
                  <!--    单选题部分    item.userAnswer    -->
                  <template v-if="item.topicType == 0">
                    <div @click="setChoiceAnswer(item,answerItem,'choice')" class="option_item pointer" v-for="(answerItem, answerIndex) in item.ccTopicOptionList" :key="answerIndex">
                      <div :class="{'option_selected':answerItem.isChecked}" class="option_label">{{labelList[answerIndex]}}</div>
                      <div class="option_value line_feed" v-html="$renderedDescription(answerItem.optionValue)"></div>
                    </div>
                  </template>
                  <!--    多选题部分   multiAnswers     -->
                  <template v-if="item.topicType == 1">
                    <div @click="setChoiceAnswer(item,answerItem,'multiChoice')" class="option_item pointer"  v-for="(answerItem, answerIndex) in item.ccTopicOptionList" :key="answerIndex">
                      <div :class="{'option_selected':answerItem.isChecked}" class="option_label">{{labelList[answerIndex]}}</div>
                      <div class="option_value line_feed" v-html="$renderedDescription(answerItem.optionValue)"></div>
                    </div>
                  </template>
                </template>
                <template v-if="submitType==2">
                  <!--    填空题部分        -->
                  <div v-if="item.topicType == 3">
                    <div class="blank_item" v-for="(optionIndex) in item.optionCount" :key="optionIndex">
                      <div class="answer_content line_feed"
                           v-html="`${optionIndex}.${$renderedDescription(item.multiAnswers[optionIndex - 1]?item.multiAnswers[optionIndex - 1] : '')}`"
                      ></div>
                    </div>
                  </div>
                  <!--    单选题部分    item.userAnswer    -->
                  <template v-if="item.topicType == 0">
                    <div class="option_item pointer" v-for="(answerItem, answerIndex) in item.ccTopicOptionList" :key="answerIndex">
                      <div :class="{'option_selected':answerItem.isChecked,'right_bg':answerItem.isChecked && item.right,'wrong_bg':answerItem.isChecked && !item.right}" class="option_label">{{labelList[answerIndex]}}</div>
                      <div class="option_value line_feed" v-html="$renderedDescription(answerItem.optionValue)"></div>
                    </div>
                  </template>
                  <!--    多选题部分   multiAnswers     -->
                  <template v-if="item.topicType == 1">
                    <div class="option_item pointer"  v-for="(answerItem, answerIndex) in item.ccTopicOptionList" :key="answerIndex">
                      <div :class="{'option_selected':answerItem.isChecked,'right_bg':answerItem.isChecked && item.trueAnswer.includes(answerItem.optionLabel),'wrong_bg':answerItem.isChecked && !item.trueAnswer.includes(answerItem.optionLabel)}" class="option_label">{{labelList[answerIndex]}}</div>
                      <div class="option_value line_feed" v-html="$renderedDescription(answerItem.optionValue)"></div>
                    </div>
                  </template>
                </template>


                <!--    判断题部分        -->
                <el-radio-group
                  v-removeAriaHidden
                  :disabled="submitType == 2"
                  v-if="item.topicType == 2"
                  v-model="item.userAnswer"
                >
                  <el-radio :label="'正确'">对</el-radio>
                  <el-radio :label="'错误'">错</el-radio>
                </el-radio-group>
              </div>
              <div class="detail_box" v-if="submitType == 2">
                <!--  答案：  -->
                <template v-if="item.answer">
                  <div v-if="$isIncludesHtml(item.answer)" class="score_got" v-html="`${item.answer.slice(0,3)}答案：${$renderedDescription(item.answer.slice(3))}`"
                  ></div>
                  <div v-else class="score_got" v-html="`答案：${$renderedDescription(item.answer)}`"></div>
                </template>
                <!--  解析：  -->
                <template v-if="item.resolve">
                  <div v-if="$isIncludesHtml(item.resolve)" class="resolve_text"
                       v-html="`${item.resolve.slice(0,3)}解析：${$renderedDescription(item.resolve.slice(3))}`"
                  ></div>
                  <div v-else class="resolve_text" v-html="`解析：${$renderedDescription(item.resolve)}`"></div>
                </template>
                <!--  准确率：  -->
                <div class="answer_range">准确率：{{ item.answerRange }}%</div>
              </div>
            </div>
          </div>
        </div>
        <div class="switching_btns">
          <div class="btns_left">
            <div v-if="answerExamData[0].isDeleted" @click="addWrongTopic(answerExamData[0].id)" class="btn_orange">加入错题集</div>
            <div v-else class="btn_blue" @click="sureRemove(answerExamData[0].id)">移出错题集</div>
          </div>
          <div class="btns_right">
            <div
              v-if="topicIndex > 0"
              @click="preQuestion"
              class="operation_btn"
            >
              上一题
            </div>
            <div
              v-if="topicIndex < this.examPaperList.length - 1"
              @click="nextQuestion"
              class="operation_btn"
            >
              下一题
            </div>
          </div>

        </div>
      </div>
      <div class="main_right">
        <div class="title">
          答题卡
        </div>
        <div class="sheet_question_list">
          <!--     作答详情       -->
          <div class="sheet_answer_collect" v-if="submitType==1">
            <div v-for="(childItem, childIndex) in examPaperList" :key="childIndex">
              <div
                @click="jumpToDetail(childIndex)"
                v-if="childItem.topicType == 1"
                :class="{ 'selected': childItem.multiAnswers.length > 0 }"
                class="sheet_answer_collect_item"
              >
                {{ childIndex + 1 }}
              </div>
              <div
                @click="jumpToDetail(childIndex)" v-else-if="childItem.topicType == 3"
                :class="{'selected':childItem.multiAnswers &&childItem.multiAnswers.length == childItem.optionCount && !childItem.multiAnswers.includes(''),}"
                class="sheet_answer_collect_item"
              >
                {{ childIndex + 1 }}
              </div>
              <div
                @click="jumpToDetail(childIndex)"
                v-else
                :class="{ 'selected': childItem.userAnswer }"
                class="sheet_answer_collect_item"
              >
                {{ childIndex + 1 }}
              </div>
            </div>
          </div>
          <!--     作答详情       -->
          <div class="sheet_answer_collect" v-if="submitType == 2">
            <div v-for="(childItem, childIndex) in examPaperList" :key="childIndex">
              <div
                @click="jumpToDetail(childIndex)"
                v-if="childItem.topicType == 1"
                :class="{
                    'right_answer': childItem.right,
                    'wrong_answer': !childItem.right
                  }"
                class="sheet_answer_collect_item"
              >
                {{ childIndex + 1 }}
              </div>
              <div
                @click="jumpToDetail(childIndex)" v-else-if="childItem.topicType == 3"
                :class="{
                    'right_answer': childItem.right,
                    'wrong_answer': !childItem.right
                    }"
                class="sheet_answer_collect_item"
              >
                {{ childIndex + 1 }}
              </div>
              <div
                @click="jumpToDetail(childIndex)"
                v-else
                :class="{
                    'right_answer': childItem.right,
                    'wrong_answer': !childItem.right
                  }"
                class="sheet_answer_collect_item"
              >
                {{ childIndex + 1 }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="submitType==1" @click="submitAnswer" class="submit_btn">
          完成错题练习
        </div>
        <div v-if="submitType==2" @click="routeBack" class="submit_btn">
          返回错题集
        </div>
      </div>
    </div>
    <!--  插入公式  -->
    <addFormulaOptionDrawer :open.sync="showFormulaDrawer" @formulaReturn="formulaReturn"></addFormulaOptionDrawer>
  </div>
</template>

<script>
import addFormulaOptionDrawer from '@/views/ExaminationModule/components/addFormulaOptionDrawer'
import { removeMistakeTopicApi } from '@/api/ExaminationModule/wrongQuestion'

export default {
  name: 'redoAnswerComponent',
  props: {
    redoTopicList: {
      type: Array,
      default: () => {
        return []
      }
    },
    courseId: {
      type: [String, Number],
      default: ''
    }
  },
  components: {
    addFormulaOptionDrawer
  },
  data() {
    return {
      labelList: this.$store.getters.EN,
      answerExamData: [],
      submitType: 1,
      topicIndex: 0,
      nowOptionIndex: 0,
      showFormulaDrawer: false,
      nowItem: {}
    }
  },
  watch: {
    redoTopicList: {
      handler(newValue) {
        this.examPaperList = newValue
        this.handleExamData(this.topicIndex)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    addWrongTopic(id) {
      this.answerExamData[0].isDeleted = false
      this.examPaperList.forEach(item => {
        if (item.id == id) {
          item.isDeleted = false
        }
      })
      this.$modal.msgSuccess('加入成功')
    },
    sureRemove(id) {
      this.$confirm('是否确认移出已选中的错题，移出后将不可恢复？', '移出错题集确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.answerExamData[0].isDeleted = true
        this.$modal.msgSuccess('移出成功')
        this.examPaperList.forEach(item => {
          if (item.id == id) {
            item.isDeleted = true
          }
        })
      }).catch(() => {
        this.$modal.msgInfo('已取消')
      })
    },
    async removeMistakeTopic(ids) {
      const loading = this.$loading({
        lock: true,
        text: '正在处理...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let res = await removeMistakeTopicApi(this.courseId, ids)
        const { code } = res
        if (code == 200) {
          this.submitType = 2
          console.log('移出成功')
        }
      } catch (e) {
        console.log(e)
      } finally {
        loading.close()
      }
    },
    routeBack() {
      this.$router.go(-1)
    },
    formulaReturn(e) {
      this.answerExamData.forEach(item => {
        if (item.id == this.nowItem.id) {
          item.multiAnswers[this.nowOptionIndex] = e
        }
      })
    },
    clearFormulaValue(nowItem, optionIndex) {
      nowItem.multiAnswers.splice(optionIndex, 1, '')
    },
    getValueByFormula(item, index) {
      this.showFormulaDrawer = true
      this.nowOptionIndex = index
      this.nowItem = item
    },
    setChoiceAnswer(item, answerItem, type) {
      if (this.submitType == 2) {
        return
      }
      if (type == 'choice') {
        if (answerItem.isChecked) {
          return
        }
        item.ccTopicOptionList.forEach(optionItem => {
          optionItem.isChecked = optionItem.id == answerItem.id
          if (optionItem.isChecked) {
            item.userAnswer = optionItem.optionLabel
          }
        })
      }
      if (type == 'multiChoice') {
        let multiAnswers = []
        item.ccTopicOptionList.forEach(optionItem => {
          if (optionItem.id == answerItem.id) {
            optionItem.isChecked = !optionItem.isChecked
          }
          if (optionItem.isChecked) {
            multiAnswers.push(optionItem.optionLabel)
          }
        })
        item.multiAnswers = multiAnswers
      }
    },
    jumpToDetail(childIndex) {
      this.topicIndex = childIndex
      this.handleExamData(this.topicIndex)
    },
    //根据下标处理当前考试题目的数据
    handleExamData(topicIndex) {
      this.answerExamData = [this.examPaperList[topicIndex]]
    },
    //上一题
    preQuestion() {
      if (this.topicIndex == 0) {
        return
      }
      this.topicIndex--
      this.handleExamData(this.topicIndex)
    },
    // 下一题
    nextQuestion() {
      if (this.topicIndex + 1 == this.examPaperList.length) {
        return
      }
      this.topicIndex++
      this.handleExamData(this.topicIndex)
    },
    submitAnswer() {
      let ids = []
      this.examPaperList.forEach(item => {
        if (item.isDeleted) {
          ids.push(item.id)
        }
        if (item.topicType == 3) {
          let groups = []
          item.ccTopicOptionList.forEach(optionItem => {
            groups.push(optionItem.group)
          })
          item.right = this.checkFillInBlankCorrectWithGrouping(item.answer, item.multiAnswers, groups)
          console.log('right', this.checkFillInBlankCorrectWithGrouping(item.answer, item.multiAnswers, groups))
        } else {
          item.right = this.returnRight(item.topicType, item.answer, item.multiAnswers, item.userAnswer)
        }

      })
      if (ids.length > 0) {
        this.removeMistakeTopic(ids.join(','))
      } else {
        console.log(this.examPaperList)
        this.submitType = 2
      }
    },
    returnRight(type, answer, multiAnswers, userAnswer) {
      if (type == 0) {
        return answer == userAnswer
      }
      if (type == 1) {
        // 将字符串转为字符数组并排序
        const sortedStr = answer.split('').sort().join('')
        // 将传入的数组排序后拼接
        const sortedArr = multiAnswers.sort().join('')
        return sortedStr === sortedArr
      }
      if (type == 2) {
        return answer == userAnswer
      }
    },
    /**
     * 支持分组乱序匹配的填空题检查
     * @param {string} standardAnswer - 标准答案字符串，用 | 分隔
     * @param {Array<string>} userAnswers - 用户答案数组，与空位顺序一致
     * @param {Array<number|null>} groups - 每个空所属的组号
     * @returns {boolean}
     */
    checkFillInBlankCorrectWithGrouping(standardAnswer, userAnswers, groups = null) {
      console.log('checkFillInBlankCorrectWithGrouping', standardAnswer, userAnswers, groups)

      // 处理边界情况
      if (!standardAnswer && (!userAnswers || userAnswers.length === 0)) {
        return true // 都没有答案，算正确
      }
      if (!standardAnswer || !userAnswers) {
        return false // 一方有答案，另一方没有，算错误
      }

      const standardAnswers = standardAnswer.split('|').map(ans => ans.trim())
      const totalBlanks = standardAnswers.length

      if (userAnswers.length !== totalBlanks) {
        return false // 答案数量不匹配
      }

      // 如果没有传 groups，默认每个空独立
      const effectiveGroups = groups || standardAnswers.map((_, i) => i)
      const groupMap = new Map()

      // 按组聚合答案
      for (let i = 0; i < totalBlanks; i++) {
        const groupKey = effectiveGroups[i] !== null && effectiveGroups[i] !== undefined
          ? effectiveGroups[i]
          : 'null'

        if (!groupMap.has(groupKey)) {
          groupMap.set(groupKey, { user: [], standard: [] })
        }

        const bucket = groupMap.get(groupKey)
        bucket.user.push(userAnswers[i].trim())
        bucket.standard.push(standardAnswers[i])
      }

      // 检查每个组
      for (const [, { user, standard }] of groupMap) {
        const unmatchedStandard = [...standard]

        for (const userAns of user) {
          let matched = false

          // 尝试精确匹配
          const exactMatchIndex = unmatchedStandard.findIndex(stdAns =>
            stdAns === userAns
          )
          if (exactMatchIndex !== -1) {
            unmatchedStandard.splice(exactMatchIndex, 1)
            matched = true
            continue
          }

          // 尝试多选匹配（正确答案包含 &）
          for (let j = 0; j < unmatchedStandard.length; j++) {
            const stdAns = unmatchedStandard[j]
            if (stdAns.includes('&')) {
              const options = stdAns.split('&').map(opt => opt.trim())
              if (options.includes(userAns)) {
                unmatchedStandard.splice(j, 1)
                matched = true
                break
              }
            }
          }

          if (!matched) {
            return false
          }
        }
      }

      return true
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../../assets/styles/mixin.scss";

.container {
  width: 100%;
  display: flex;
  justify-content: center;
  background: #f5f6f7;
  padding-top: 24px;
  box-sizing: border-box;

  .main_content {
    width: 1200px;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .main_left {
      width: 840px;
      background: #FFFFFF;
      border-radius: 16px;
      border: 1px solid #EBEBEB;
      padding: 24px;
      box-sizing: border-box;

      .main_topic {
        width: 100%;
        height: calc(100vh - 238px);
        overflow: auto;

        .answer_list {
          width: 100%;

          .answer_question {
            .question_content {
              font-family: PingFangSC, PingFang SC, sans-serif;
              font-weight: 400;
              font-size: 16px;
              color: #333333;
            }

            .item_answer {
              width: 100%;
              margin: 22px 0 0;

              .blank_item {
                display: flex;
                align-items: center;
                margin: 10px 0;

                .formula_text {
                  min-width: 256px;
                  margin-left: 11px;
                }

                &_info {
                  min-width: 160px;
                  padding: 6px 10px;
                  box-sizing: border-box;
                  color: #a0a09f;;
                  border-radius: 8px;
                  background: #f5f7fa;
                  border: 1px solid #e4e7ed;
                  cursor: not-allowed;
                }

                &_label {
                  font-size: 14px;
                  font-weight: 400;
                  color: #a0a09f;
                }

                &_answer {
                  width: 256px;
                  margin-left: 11px;
                }

                &_right {
                  margin-left: 12px;
                }

                .answer_content {
                  font-family: PingFangSC, PingFang SC, sans-serif;
                  font-size: 16px;
                  color: #333333;
                }
              }

              .option_item {
                display: flex;
                margin-bottom: 22px;

                .option_label {
                  width: 24px;
                  height: 24px;
                  margin-right: 10px;
                  background: #FFFFFF;
                  border: 1px solid #DDDDDD;
                  border-radius: 50%;
                  font-family: PingFangSC, PingFang SC, sans-serif;
                  font-weight: 400;
                  font-size: 14px;
                  color: #999999;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                }

                .option_selected {
                  color: #68d9ff !important;
                  background: #daf1ff !important;
                  border: 1px solid #daf1ff;
                }

                .right_bg {
                  color: #ffffff !important;
                  background: #28B28B !important;
                  border: 1px solid #28B28B;
                }

                .wrong_bg {
                  color: #ffffff !important;
                  background: #FE5B59 !important;
                  border: 1px solid #FE5B59;
                }
                .option_value{
                  min-width: 0;
                  flex:1;
                  font-family: PingFangSC, PingFang SC, sans-serif;
                  font-weight: 400;
                  font-size: 16px;
                  color: rgba(0, 0, 0, 0.85);
                }
              }

              .textarea {
                width: 60%;
                font-size: 16px;
              }

              .attachment {
                width: 100%;
                padding: 25px 0 0;
                box-sizing: border-box;
                display: flex;

                &_sugest {
                  font-size: 14px;
                  font-weight: 400;
                  color: #999999;
                  margin-top: 16px;
                }

                .pictures {
                  margin-left: 10px;
                }
              }
            }

            .detail_box {
              margin-top: 10px;
              width: 100%;
              display: flex;
              flex-direction: column;
              gap: 10px 0;

              .score_got {
                font-family: PingFangSC, PingFang SC, sans-serif;
                font-weight: 400;
                font-size: 16px;
                color: #28B28B;
              }

              .resolve_text {
                font-family: PingFangSC, PingFang SC, sans-serif;
                font-weight: 400;
                font-size: 16px;
                color: #333333;
              }

              .answer_range {
                font-family: PingFangSC, PingFang SC, sans-serif;
                font-weight: 400;
                font-size: 16px;
                color: #999999;
              }
            }
          }
        }
      }

      .switching_btns {
        width: 100%;
        padding-top: 24px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .btns_left {
          display: flex;
          gap: 0 16px;

          .btn_orange {
            @include plain_hover(#FFFFFF, #FA6400, #ffffff) {
              width: 100px;
              height: 40px;
              border-radius: 8px;
              border: 1px solid #FA6400;
            }
          }

          .btn_blue {
            @include plain_hover(#FFFFFF, #4E8DFF, #ffffff) {
              width: 100px;
              height: 40px;
              border-radius: 8px;
              border: 1px solid #4E8DFF;
            }
          }
        }

        .btns_right {
          display: flex;
          gap: 0 16px;

          .operation_btn {
            @include plain_hover(#D3D2D2, #28b28b, #ffffff) {
              width: 100px;
              height: 40px;
              color: #333333;
              font-family: PingFangSC, PingFang SC, sans-serif;
              background: #FFFFFF;
              border-radius: 8px;
              border: 1px solid #D3D2D2;
            }
          }
        }
      }
    }

    .main_right {
      flex: 1;
      background: #FFFFFF;
      border-radius: 16px;
      border: 1px solid #EBEBEB;

      .title {
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 500;
        font-size: 18px;
        color: #333333;
        padding: 24px 24px 14px 24px;
        box-sizing: border-box;
        border-bottom: 1px solid #EDEFF0;
      }

      .sheet_question_list {
        width: 100%;
        height: calc(100vh - 278px);
        overflow: auto;
        padding: 24px;
        box-sizing: border-box;

        .sheet_answer_collect {
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 12px;

          &_item {
            cursor: pointer;
            user-select: none;
            margin: 0 10px 10px 0;
            width: 36px;
            height: 36px;
            background: #ffffff;
            color: #999999;
            border-radius: 50%;
            border: 1px solid #28b28b;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }

      .submit_btn {
        margin: 24px auto;
        @include btn_plain(#28B28B, #ffffff) {
          width: 296px;
          height: 40px;
          border-radius: 8px;
          font-family: PingFangSC, PingFang SC, sans-serif;
          font-weight: 500;
          font-size: 16px;
          color: #FFFFFF;
        }

        &:hover {
          background: #3ac7a0;
        }
      }
    }
  }
}

.icon_box {
  margin-left: 12px;
  width: 32px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none;
  cursor: pointer;
  border-radius: 6px;

  &:hover {
    background: #f1f1f1;
  }

  .el-icon-delete {
    font-size: 20px;
    color: #f67878;
    font-style: normal !important;
  }

  .formula_icon {
    font-size: 20px;
    color: #0b8cfc;
  }
}

.selected {
  background: #daf1ff !important;
  color: #03c4ff !important;
  border: 1px solid #daf1ff !important;
}

.right_answer {
  background: #b3fcd6 !important;
  color: #28B28B !important;
  border: 1px solid #b3fcd6 !important;
}

.wrong_answer {
  background: #FFCFCE !important;
  color: #E95756 !important;
  border: 1px solid #FFCFCE !important;
}
</style>
<style>
.color_orange {
  color: #EF7D00;
}
</style>
